$(function ready() {
    // 动态获取入库类型 1-入库 2-出库
    writeInOrOutTypeSelect($("#searchType"), 1);
    // 动态获取入库类型 1-入库 2-出库
    writeInOrOutTypeSelect($("#addType"), 1);

    // 查询并更新供应商下拉框的选项
    writeSupplierSelect($("#searchSupplier"));
    // 查询并更新供应商下拉框的选项
    writeSupplierSelect($("#addSupplier"));

    // 查询并更新仓库下拉框的选项,product.js重复，无需重复加载
    // writeRepositorySelect($("#searchRepository"));
    // 查询并更新仓库下拉框的选项
    writeRepositorySelect($("#addRepository"));

    // 设置入库时间选择器
    setDateSelector($("#searchTime"));

    // 模态框展示时，如果列表中只有表头，则新增一行
    $('#addModal').on('shown.bs.modal', function () {
        if ($("#addInboundList").find("tbody tr").length > 0) {
            return;
        }
        // 在这里执行数据初始化代码
        addOneTr($("#addInboundList"));
    });

    /**
     * 列表数据
     */
    $("#inboundTable").bootstrapTable({
        url: "/inbound/list",
        method: "get",
        pagination: true,   //是否显示分页（*）
        pageSize: 10,       //每页的记录行数（*）
        pageList: [10, 20, 50, 100, 'All'], //可供选择的每页的行数（*）
        sidePagination: "client",    //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                    //初始化加载第一页，默认第一页
        classes: "table table-bordered table-striped table-condensed table-hover",
        uniqueId: "id",
        queryParams: function (params) {//默认参数设置
            return getParams(params);
        },
        rowStyle: function (row, index) {
            return getRowStyle(row, index);
        },
        onDblClickCell: function (field, value, row, $element) {
            return onDblClickCell(field, value, row, $element);
        },
        columns: [{
            title: "id",
            field: "id",
            visible: false
        }, {
            title: "入库编号",
            field: "no"
        }, {
            title: "入库类型id",
            field: "typeId",
            visible: false
        }, {
            title: "入库类型",
            field: "typeName",
        }, {
            title: "商品id",
            field: "productId",
        }, {
            title: "商品名称",
            field: "productName",
        }, {
            title: "计划入库数量",
            field: "planNum"
        }, {
            title: "实际入库数量",
            field: "actualNum"
        }, {
            title: "是否完成",
            field: "isFinish",
            formatter(value, row, index) {
                return value === 1 ? '已完成' : '未完成';
            }
        }, {
            title: "入库成本：元",
            field: "costYuan"
        }, {
            title: "供应商id",
            field: "supplierId",
        }, {
            title: "供应商",
            field: "supplierName"
        }, {
            title: "仓库id",
            field: "repositoryId",
        }, {
            title: "仓库",
            field: "repositoryName"
        }, {
            title: "备注",
            field: "note"
        }, {
            title: "入库时间",
            field: "createTime"
        }, {
            title: "删除位",
            field: "isDelete",
            visible: false
        }, {
            field: 'operate',
            title: '操作',
            align: 'center',
            valign: 'middle',
            width: 200,
            events: {
                'click #update': function (e, value, row, index) {
                    updateOne(e, value, row, index);
                },
                'click #delete': function (e, value, row, index) {
                    deleteOne(e, value, row, index);
                }
            },
            formatter: function (value, row, index) {
                let result = "";
                result += '<button id="update" class="btn btn-info" data-toggle="modal" data-target="#updateModal">保存修改</button>';
                let deleteStr = !row.isDelete ? '删除' : '恢复';
                result += '<button id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal" style="margin-left:10px;">' + deleteStr + '</button>';
                return result;
            }
        }]
    });


    /**
     * 设置样式
     */
    function getRowStyle(row, index) {
        if (row.isDelete !== 0) {
            return {css: {"background-color": 'Gray'}};
        } else if (row.isFinish == 0) {
            return {css: {"background-color": 'OrangeRed'}};
        }
        return {};
    }

    /**
     * 这里可以自定义处理查询参数，包括添加默认参数
     * @param params
     * @returns {*}
     */
    function getParams(params) {
        let picker = $("#searchTime").data('daterangepicker');
        let format = 'YYYY-MM-DD HH:mm:ss'
        params = $.extend({}, params, {
            no: $("#searchNo").val(),
            productName: $("#searchProductName").val(),
            typeId: $("#searchType").val(),
            isFinish: $("#searchIsFinish").val(),
            supplierId: $("#searchSupplier").val(),
            repositoryId: $("#searchRepository").val(),
            isDelete: $("#searchIsDelete").val(),
            startTime: picker.startDate.format(format),
            endTime: picker.endDate.format(format)
        });
        return params;
    }

});


/**
 * 按下Enter查询
 */
$(document).keyup(function (event) {
    if (event.keyCode == 13) {
        search();
    }
});

/**
 * 查询
 */
function search() {
    $("#inboundTable").bootstrapTable('refresh')
}

/**
 * 查询按钮点击事件
 */
$("#search").click(search);


/**
 * 重置按钮
 */
$("#reset").click(function () {

    $("#searchNo").val("");
    $("#searchProductName").val("");

    $("#searchType").val("");
    $("#searchType").selectpicker("refresh");

    $("#searchTime").val("");

    $("#searchSupplier").val("");
    $("#searchSupplier").selectpicker("refresh");
    $("#searchRepository").val("");
    $("#searchRepository").selectpicker("refresh");
    $("#searchIsFinish").val("");
    $("#searchIsFinish").selectpicker("refresh");
    $("#searchIsDelete").val("0");
    $("#searchIsDelete").selectpicker("refresh");
})

/**
 * 批量新增按钮
 */
$("#addList").click(function () {
    let tableData = getTableData($("#addInboundList"));
    // 为每条记录添加入库类型
    let typeId = $("#addType").val();
    tableData.forEach(row => {
        row.typeId = typeId;
    });
    $.post({
        url: '/inbound/addList',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(tableData),
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
    $("#addModal").modal('hide');
})


/**
 * 模糊搜索商品名称，
 * 并展示符合条件的商品列表
 */
$("#addProductName").on("input change", function () {
    writeProductUl($("#addProductId"), $("#addProductName"), $("#addProduct"));
});


/**
 * 添加一行
 */
$("#addOneTr").click(function () {
    addOneTr($("#addInboundList"));
});


/**
 * 表格内元素的点击事件
 * @param field
 * @param value
 * @param row
 * @param element
 */
function onDblClickCell(field, value, row, $element) {
    // 不处理的字段
    if (field == 'id' || field == 'productId' || field == 'supplierId' || field == 'repositoryId' || field == 'no' || field == 'typeName' || field == 'isFinish') {
        return;
    }
    textToInput($("#inboundTable"), field, row, $element);
}

/**
 * bootstrap中，修改某个字段时，
 * 同步中修改相关的字段，同时修改bootstrap中的row
 * @type {{syncData: Window.inboundTable.syncData}}
 */
window.inboundTable = {
    syncData: function ($table, fieldName, row, $td) {
        // 当前行所有td
        let $tds = $td.parent().children();
        // 修改名称时，同步id数据
        switch (fieldName) {
            case 'productName':
                row["productId"] = $($tds[getTdIndexByFiled($table, "productId")]).text();
                break;
            case 'supplierName':
                row["supplierId"] = $($tds[getTdIndexByFiled($table, "supplierId")]).text();
                break;
            case 'repositoryName':
                row["repositoryId"] = $($tds[getTdIndexByFiled($table, "repositoryId")]).text();
                break;
        }
    }
}

/**
 * 修改当前行数据
 * @param e
 * @param value
 * @param row
 * @param index
 */
function updateOne(e, value, row, index) {
    $.post({
        url: '/inbound/updateOne',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(row), // 将对象转换为JSON字符串
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
}

/**
 * 删除或恢复 当前行
 * @param e
 * @param value
 * @param row
 * @param index
 */
function deleteOne(e, value, row, index) {
    $.post({
        url: '/inbound/deleteOne',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            id: row.id,
            no: row.no,
            productId: row.productId,
            repositoryId: row.repositoryId,
            isDelete: row.isDelete == 0 ? 1 : 0
        }),
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
}


